package com.yuyu.helper;

import com.yuyu.annotation.Autowired;
import com.yuyu.util.ReflectionUtil;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 依赖注入助手类
 * author:yuyu
 * Date:2018/10/19
 * Time:22:28
 */
public class IocHelper {

    static {
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if (null != beanMap && !beanMap.isEmpty()) {
            for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
                Class<?> beanClass = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();

                Field[] beanFields = beanClass.getDeclaredFields();
                if (ArrayUtils.isNotEmpty(beanFields)) {
                    for (Field beanFild : beanFields) {
                        if (beanFild.isAnnotationPresent(Autowired.class)) {
                            Class<?> beanFildClass = beanFild.getType();
                            Object beanFildInstance = beanMap.get(beanFildClass);
                            if (beanFildInstance != null) {
                                ReflectionUtil.setField(beanInstance, beanFild, beanFildInstance);
                            }
                        }
                    }
                }
            }
        }
    }
}
